import axios,  { type AxiosRequestConfig, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios';
import leemLibs from '.';
import router from '@/router';

const request = axios.create({
    baseURL : import.meta.env.VITE_BASE_API_URL + import.meta.env.VITE_GETAWAY,
    timeout : 5000,
    headers : {
        'Content-Type' : 'application/json',
    }
});


//请求拦截
request.interceptors.request.use(
    config => {
        config.headers[import.meta.env.VITE_TOKEN_KEY] = leemLibs.Token.get();
        return config;
    },
    error => {
        ElMessage.error('网络请求异常');
        return Promise.reject(error);
    }
);

//响应拦截
request.interceptors.response.use(
    response => {
        const {status, data : {code, data, message}} = response
        if (status !== 200) {
            ElMessage.error('网络请求异常');
            return Promise.reject(response);
        };
        //token错误
        if ([400101, 400102].includes(code)) {
            console.log(router);
            router.replace('/login');
            return Promise.reject({data, code, message});
        };

        if (code !== 0) {//code = 0 表示请求成功
            ElMessage.error(message);
            return Promise.reject({data, code, message});
        };
        return data;
    },
    error => {
         ElMessage.error('网络请求异常');
        return Promise.reject(error);
    }
)


const leemAxios = <T>(config : AxiosRequestConfig) : Promise<T> => {
    return new Promise((r,j) => {
        request(config).then(res => {
            r(res as T);
        }).catch(err => {
            j(err);
        });
    });
};


export {
    leemAxios
};